package com.gomokult.service.impl;

import com.gomokult.dao.impl.UserDAOImpl;
import com.gomokult.entity.User;
import com.gomokult.exception.IllegalOperationException;
import com.gomokult.exception.InvalidIDException;
import com.gomokult.exception.UserRegisteredException;
import com.gomokult.service.GameplayService;

public class GameplayServiceImpl implements GameplayService {
	private GameplayServiceImpl() {}
	private static final GameplayServiceImpl singleton= new GameplayServiceImpl();
	public static GameplayServiceImpl getSingleton() { return singleton; }

    @Override
    public int getUserLevel(int userID) throws InvalidIDException {
        User user = UserDAOImpl.getSingleton().selectUserbyID(userID);
        int score = (int) (user.getScore()*8/(UserDAOImpl.getSingleton().selectBestscore()+1)*0.6);
        int win = (int) (user.getWinGames()*8/(user.getTotalGames()+1)*0.4);
        return (score+win)/2;
    }

    @Override
    public void setScore(int userID, int score) throws InvalidIDException {
        User user = UserDAOImpl.getSingleton().selectUserbyID(userID);
        user.setScore(score);
        try {
            UserDAOImpl.getSingleton().updateUser(userID,user);
        } catch (IllegalOperationException e) {
            throw new RuntimeException(e);
        } catch (UserRegisteredException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int countScore(int userID, int deltaScore) throws InvalidIDException {
        User user = UserDAOImpl.getSingleton().selectUserbyID(userID);
        user.setScore(user.getScore()+deltaScore);
        try {
            UserDAOImpl.getSingleton().updateUser(userID,user);
        } catch (IllegalOperationException e) {
            throw new RuntimeException(e);
        } catch (UserRegisteredException e) {
            throw new RuntimeException(e);
        }
        return user.getScore();
    }
}
